<script setup lang="ts">
import { ApiDetail } from '@/api/api-manage/detail'
import axios from 'axios'
import { message } from '@/utils/message'
import { dayjs, UploadRawFile, UploadUserFile } from 'element-plus'
import { generateApiLog } from '../../useApiLog'
import { useUserStore } from '@/store/modules/user'
import { getToken } from '@/utils/auth'
import { addLog } from '@/api/api-manage/log'

const props = defineProps<{
  data: ApiDetail
}>()

const fileList = ref<UploadUserFile[]>([] as any)
const uploadRef = ref()
const objectB64 = ref()
const buttonLoading = ref(false)
const textLoading = ref(false)
const textRes = ref('')
const isSuccess = ref(false)
const url = ref(null)
const b64Data = ref(null)

/**
 * 上传文件方法
 * @param options
 */
const requestFile = async (options) => {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  textRes.value = ''
  b64Data.value = null
  isSuccess.value = false
  objectB64.value = null
  url.value = null
  buttonLoading.value = true
  textLoading.value = true
  const reader = new FileReader()
  reader.readAsDataURL(options.file)
  reader.onload = () => {
    b64Data.value = reader.result
  }
  const { file } = options
  const formData = new FormData()
  formData.append('img1', file)
  formData.append('load_weight', 'true')
  message('正在进行人脸库对比识别', { type: 'info' })
  let startTime = performance.now()
  const requestTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let res = '0'
  let resCode = 500
  axios
    .post(props.data.serverProdPath + props.data.serverUri, formData)
    .then((response) => {
      if (response?.data?.matchedB64 != null && response?.data?.matchedB64 != '') {
        url.value = 'data:image/jpeg;base64,' + response.data.matchedB64
        message('人脸匹配成功', { type: 'success' })
        isSuccess.value = true
        let similar: number = 1 - response.data.distance
        similar = similar * 100
        textRes.value = '人脸匹配成功，相似度：' + similar.toFixed(2) + '%'
        res = '1'
        resCode = 200
      } else if (response?.data?.matchedB64 == '') {
        message('未匹配到人脸', { type: 'warning' })
        textRes.value = '未匹配到人脸'
        res = '1'
        resCode = 200
      } else {
        message('接口存在问题无法调用', { type: 'error' })
        res = '0'
        resCode = 500
      }
    })
    .catch((err) => {
      res = '0'
      resCode = 500
      message('接口存在问题无法调用', { type: 'error' })
    })
    .finally(() => {
      let endTime = performance.now()
      let duration = endTime - startTime
      const endDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      let userBy = '在线体验'
      if (getToken() != null && getToken() != '') {
        userBy = useUserStore().username + userBy
      }
      const log = generateApiLog(
        props.data,
        requestTime,
        endDateTime,
        duration,
        userBy,
        res,
        resCode,
        '2'
      )
      addLog(log)
      textLoading.value = false
      buttonLoading.value = false
    })
}

const beforeUpload = (rawFile: UploadRawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/jpg') {
    return true
  } else {
    message('请上传jpg图片', { type: 'warning' })
    return false
  }
}
</script>

<template>
  <el-form>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          action="#"
          :file-list="fileList"
          :show-file-list="false"
          :http-request="requestFile"
          accept=".jpg,.jpeg"
          :before-upload="beforeUpload"
        >
          <el-button v-loading="buttonLoading" type="primary">上传人脸图片</el-button>
        </el-upload>
      </el-col>
      <el-col v-if="b64Data != null" :span="12">
        <el-form-item label="上传的图片：">
          <el-image :src="b64Data" fit="contain" style="width: 200px; height: 200px" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-form-item />
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item v-loading="textLoading" label="识别结果">
          <el-input v-model="textRes" type="textarea" :rows="3" />
        </el-form-item>
      </el-col>
      <el-col v-if="isSuccess" :span="12">
        <el-form-item v-loading="textLoading" label="人脸库中匹配到的图片：">
          <el-image :src="url" fit="contain" style="width: 200px; height: 200px" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
